<%@ taglib prefix="wctags" tagdir="/WEB-INF/tags" %>
<%@ taglib uri="http://www.ptc.com/windchill/taglib/picker" prefix="p"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.ptc.com/windchill/taglib/components" prefix="jca"%>
<%@ taglib uri="http://www.ptc.com/windchill/taglib/wrappers" prefix="w"%>
<%@ taglib uri="http://www.ptc.com/windchill/taglib/fmt" prefix="fmt"%>
<%@ page import="com.ptc.netmarkets.util.beans.NmCommandBean,
                 com.ptc.netmarkets.util.misc.NmAction,
                 com.ptc.netmarkets.util.misc.NmHTMLActionModel,
                 com.ptc.netmarkets.util.misc.NmActionServiceHelper,
                 com.ptc.netmarkets.util.misc.NmContext,
                 com.ptc.netmarkets.util.misc.NmContextItem,
                 com.ptc.netmarkets.user.NmUser,                                  
                 com.ptc.netmarkets.work.NmWorkItemCommands,
                 com.ptc.netmarkets.work.workResource,
                 java.util.HashMap,
                 java.util.Iterator,
                 java.util.List,
				 java.util.ArrayList,
                 java.util.ResourceBundle,
                 com.ptc.netmarkets.model.NmOid,
                 java.util.Enumeration,                                                                                     
                 wt.workflow.work.WorkItem,
                 wt.fc.WTObject,
                 wt.inf.container.WTContainer,                                                   
                 wt.inf.container.WTContained,
				 wt.fc.Persistable,com.ptc.core.ui.validation.UIValidationStatus"				 
%>

<jsp:useBean id="nmcontext" class="com.ptc.netmarkets.util.beans.NmContextBean" scope="request"/>
<jsp:useBean id="objectBean" class="com.ptc.netmarkets.util.beans.NmObjectBean" scope="request"/>
<jsp:useBean id="localeBean" class="com.ptc.netmarkets.util.beans.NmLocaleBean" scope="request"/>

<%!
  private static final String WORK_STEP_RESOURCE = "com.ptc.netmarkets.work.workResource";
%>

<fmt:setLocale value="${localeBean.locale}"/>
<fmt:setBundle basename="com.ptc.netmarkets.work.workResource" />
<fmt:message var="REASSIGN_TO_LABEL" key="REASSIGN_TO_LABEL"/>
<fmt:message var="REASON_FOR_REASSIGNMENT" key="REASON_FOR_REASSIGNMENT"/>

<%//

boolean multiReassignWiz = request.getAttribute("MULTI") != null;
NmCommandBean cb = new NmCommandBean();
cb.setCompContext(nmcontext.getContext().toString());
cb.setRequest(request);
NmOid oid = cb.getPrimaryOid();
ResourceBundle workStepRB = ResourceBundle.getBundle(WORK_STEP_RESOURCE, localeBean.getLocale());
NmContext context = nmcontext.getContext();
NmContextItem ci = (NmContextItem)context.getContextItems().get(0);
List oids = cb.getSelectedOidForPopup();
NmOid workItemOid = ci.getOid();
WTObject wtobj = null;
WTContainer container = null;
boolean isContextObtained = true;

if( workItemOid != null ){
	wtobj = (WTObject) workItemOid.getRef();
}

if(wtobj!=null)
{
	/* SPR # 1481042 : No user is able to reassign Tasks generated by Routing process of Packages.*/
	if (!(wtobj instanceof WorkItem))
	{
		if(!(wtobj instanceof WTContained))
		{		
			isContextObtained = false;
		}	
	}
}else{
	isContextObtained = false;
}

//isContextObtained = false;
if(!isContextObtained)
{
	WorkItem wi = null;
	for (Iterator i = oids.iterator(); i.hasNext();) {
		NmOid selectedOid = (NmOid)i.next();
		WTObject wtTempObj = (WTObject)selectedOid.getRef();
		WTContainer Prevcontainer = container;
		if(wtTempObj instanceof WorkItem)
		{
			wi = (WorkItem) wtTempObj;
			try
			{
				container = ((WTContained) wi.getSource().getObject()).getContainer();
			}catch(Exception e)
			{%>
					<SCRIPT LANGUAGE="JAVASCRIPT">
						alert('<%= workStepRB.getString(workResource.HAS_INVALID_WORKITEMS) %>');
						window.close();
					</SCRIPT>
			<%}
		   
			if(container!=null)
			{
			    if(!container.equals(Prevcontainer))
			    {
					if(Prevcontainer!=null)
					{
						%>				   
						<SCRIPT LANGUAGE="JAVASCRIPT">
							alert('<%= workStepRB.getString(workResource.HAS_INVALID_WORKITEMS) %>');
							window.close();
						</SCRIPT>					
						<%
					}					   
			    }
			}
		}
	}
	workItemOid = new NmOid((Persistable)container);		
}

if (wtobj instanceof WorkItem)
{
	WorkItem workitem = (WorkItem) wtobj;
	container = ((WTContained) workitem.getSource().getObject()).getContainer();
}
if( container!=null && !(container instanceof wt.inf.team.ContainerTeamManaged) )
{
%>
	<SCRIPT LANGUAGE="JAVASCRIPT">
		alert('<%= workStepRB.getString(workResource.WORKITEM_REASSIGNMENT_ERROR) %>');
		window.close();
	</SCRIPT>
<%
}else{
	Enumeration teamMembers = NmWorkItemCommands.service.getProjectMembers(workItemOid);
	ArrayList refList=new ArrayList();
	ArrayList nameList=new ArrayList();
	NmUser member;
	NmUser lastMember = new NmUser();
	while (teamMembers.hasMoreElements()){
		member = (NmUser)teamMembers.nextElement();
		if (!member.equals(lastMember)) {
		    // Shital: Using identifier as internal value instead of Name. Server methods "reassign" and "multireassign" from "StandardNmWorkItemService" has been changed accordingly.
			refList.add(member.getOid().toString() );
			nameList.add(member.getFullName());			  
		}
	   lastMember = member;		
	}		
	%>
	<c:set var="iVals" value="<%=refList%>"/>
	<c:set var="dVals" value="<%=nameList%>"/>
	
	<TABLE border="0" cellspacing="3" cellpadding="3">
		<TR>		  
			<TD align="right" valign="top">
				*<w:label name="${REASSIGN_TO_LABEL}" required="true" value="${REASSIGN_TO_LABEL}"/>
			</TD>
			<TD align="left" valign="top">			 
				<w:comboBox size="1" id="assignTo" name="assignTo" internalValues="${iVals}"  displayValues="${dVals}" required="true"/>		 
				
				<%-- get action to launch user picker --%>
				<%
					WorkItem wi = null;
					boolean allSelectedAreWorkItems = true;
					if ( allSelectedAreWorkItems ) {
					 // The search button is only available if all selected items are WorkItems.
					 /*spr:1516427: When attempting to reassign more than 6 tasks, the find button doesn't appear to allow searching for the new 	assignee*/
						cb.setSelectedInOpener(cb.getSelectedContextsForPopup());  
						NmHTMLActionModel am = NmActionServiceHelper.service.getActionModel("reassign search action", 
														wi, localeBean.getLocale(), cb.getContainer(), cb);
						List actions = am.getActions();
						NmAction reassignSearchUserAction = null;
						for (Iterator i = actions.iterator(); i.hasNext();) {
							NmAction next = (NmAction)i.next();
							if ( next.getAction().equals("reassignSearchUser") ) {
								reassignSearchUserAction = next;
								break;              
							}
						}
						reassignSearchUserAction.setEnabled(true);
						reassignSearchUserAction.setValidationStatus(UIValidationStatus.ENABLED);
						if ( reassignSearchUserAction != null ) {						  
							if(reassignSearchUserAction.isEnabled())
							{
								reassignSearchUserAction.setButton(true);               
								objectBean.setObject(reassignSearchUserAction);
								%>
								<jsp:include page="/netmarkets/jsp/util/object.jsp" flush="true"/>
								<%
								objectBean.setObject(null);  
							}
						}
					}
				  %> 

			</TD>
		</TR>
		<TR>		
			<TD align="right" valign="top">
				<w:label name="${REASON_FOR_REASSIGNMENT}" required="true" value="${REASON_FOR_REASSIGNMENT}"/>
			</TD>
			<TD align="left" valign="top">		  
				<w:textArea id="assignComments" name="assignComments" value="" cols="40" rows="4" maxLength = "2000"/>			
			</TD>
		</TR>
	</TABLE>
	<%
		if (multiReassignWiz && (oids == null || oids.size()<=0 ))
		{
			%>
			 <SCRIPT language="JavaScript">
				wfalert('<%=workStepRB.getString(workResource.NONE_SELECTED)%>');
				wfWindowClose();
			 </SCRIPT>
			<%
		}
 }%>
 
 
<SCRIPT type="text/javascript">
 
function reassignUserCallback(objects) {
	// The search picker used for the reassign task wizard is
	// single select so expect a single JSON object.
	var oid = objects.pickedObject[0].oid;
	var userName = objects.pickedObject[0].name;
	var displayName = objects.pickedObject[0].fullName;
	var principalObjectOid = objects.pickedObject[0].principalObjId;

	//alert("username: " + userName);
	//alert("displayName: " + displayName.length);
	// This is here because the user picker is currently not sending back the fullName.
	// If the fullName length is 0 then we'll fall back to displaying the username.
	if ( displayName.length == 0 ) {
		selectUser(principalObjectOid, userName);   
	}else {
		selectUser(principalObjectOid, displayName);
	}
}
 
function selectUser(userName, displayName) {
	var userList = document.forms.mainform.assignTo;
	var newOption = new Option(displayName,userName, false, true);
	var size = userList.length;
	var newList = new Array(size);
	var existingOption;

	// Save the existing options in an array.
	for (var i = 0; i < size; i++) {
		existingOption = userList.options[i];
		if ( userList.options[i] ) {
			if ( userList.options[i].value == userName ) {
				// If the user is already in the list, select the user and just return
				userList.options[i].selected = true;
				return;
			}else {
				//alert (userList.options[i].text + " " + userList.options[i].value + " " + userList.options[i].defaultSelected + " " + userList.options[i].selected);
				newList[i] = new Option(userList.options[i].text, userList.options[i].value, false, false);
			}
		}		 
	}
	
	// Empty the select list
	userList.options.length=0;

	// Add the new option to the top of the select element.
	userList.options[0]=newOption;

	// Slide the options up an index and add them to the select element
	for (var j = 0; j < newList.length; j++) {
		//alert (newList[j].text + " " + newList[j].value + " " + newList[j].defaultSelected + " " + newList[j].selected);
		userList.options[j+1]=newList[j];
	} 
} 
</SCRIPT>
